import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/Login/Login'
import SignUp from '@/views/SignUp/SignUp'
import TheLayout from '@/views/Layout/TheLayout'
import Home from '@/views/Home/Home'
import User from '@/views/System/User'
import Parameter from '@/views/System/Parameter'
import Department from '@/views/Basic/Department'
import Warehouse from '@/views/Basic/Warehouse'
import store from '../store'
import * as types from '../store/mutation-types'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/signup',
      name: 'signup',
      component: SignUp
    },
    {
      path: '',
      component: TheLayout,
      redirect: 'home',
      children: [
        {
          path: 'home',
          name: 'home',
          component: Home,
          meta: { id: 0, title: '首页' }
        }
      ]
    },
    {
      path: '/system',
      name: 'system',
      component: TheLayout,
      meta: { id: 100000000, title: '系统管理' },
      children: [
        {
          path: 'user',
          name: 'user',
          component: User,
          meta: { id: 100000001, title: '用户管理' }
        },
        {
          path: 'parameter',
          name: 'parameter',
          component: Parameter,
          meta: { id: 100000004, title: '系统参数设置' }
        }
      ]
    },
    {
      path: '/basic',
      name: 'basic',
      component: TheLayout,
      meta: { id: 106000000, title: '基础数据' },
      children: [
        {
          path: 'department',
          name: 'department',
          component: Department,
          meta: { id: 106000001, title: '部门维护' }
        },
        {
          path: 'warehouse',
          name: 'warehouse',
          component: Warehouse,
          meta: { id: 106000002, title: '仓库维护' }
        }
      ]
    }
  ]
})

// 路由匹配的回调函数
router.afterEach(to => {
  // 设置当前激活的菜单项
  const routeName = to.name
  store.commit(types.SET_ACTIVE_MENU_INDEX, routeName)

  // 设置面包屑的值
  let routeTitleList = []
  const matched = to.matched
  if (matched.length > 0 && matched[matched.length - 1].name !== 'home') {
    matched.forEach(record => routeTitleList.push(record.meta.title))

    store.commit(types.ADD_TAB, {
      name: routeName,
      id: to.meta.id,
      title: to.meta.title,
      closable: true
    })
  }
  store.commit(types.SET_ROUTE_TITLE_LIST, routeTitleList)

  // 设置当前激活的标签页
  store.commit(types.SET_CURRENT_TAB_NAME, routeName)
})

export default router
